package com.googlecode.animeclassifier;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.googlecode.animeclassifier.ui.MainPanel;

public class AnimeManager {
	private List<Anime> animes = new ArrayList<Anime>();
	private File[] roots;

	/**
	 * should modify
	 * @param args
	 */
	public AnimeManager(String[] args) {
		roots = new File[args.length];
		for(int i = 0; i < args.length; i++) {
			roots[i] = new File(args[i]);
		}
		loadAnime();
	}
	
	private void loadAnime() {
		for(File root: roots) {
			traverse(root);
		}
	}
	
	public void go() {
		final AnimeManager am = this;
		
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MainPanel.createAndShowGUI(am);
            }
        });
	}

	public void traverse(File f) {
		if(f == null) return;
		
		if(f.isDirectory()) {
			for(File one: f.listFiles()) {
				traverse(one);
			}
		} else {
			try {
				if(Anime.isVideo(f.getAbsolutePath())) {
					Anime anime = new Anime(f.getAbsolutePath());
					animes.add(anime);
				}
			} catch(Exception e) {}
		}
	}
	
	public void playAnime(Anime anime) {
		Runtime runtime = Runtime.getRuntime();
		try {
			FileWriter fw = new FileWriter("tmp.bat");
			fw.append("\"" + anime.getFile().getAbsolutePath() + "\"");
			fw.flush();
			fw.close();
			runtime.exec("tmp.bat");
//			file.delete();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void playAnime(int idx) {
		playAnime(animes.get(idx));
	}
	
	/**
	 * @return the animes
	 */
	public List<Anime> getAnimes() {
		return animes;
	}
	
	public List<Anime> getAnimesWithRegex(String regex) {
		List<Anime> ret = new ArrayList<Anime>();
		
		for(Anime anime: animes) {
			if(anime.isValid(regex)) ret.add(anime);
		}
		
		return ret;
	}
	

	/**
	 * @return the roots
	 */
	public File getRoot() {
		return roots[0];
	}
	
	public void setRoot(String str) {
		roots[0] = new File(str);
		clear();
		loadAnime();
	}
	
	private void clear() {
		this.animes = null;
	}
	
	private void refresh() {
		clear();
		loadAnime();
	}
}
